//
//  UIView+RxExtection.swift
//  YKSwiftRxExtection
//
//  Created by edward on 2022/1/5.
//

import UIKit
import RxSwift
import RxCocoa

extension Reactive where Base: UIView {
    
    public func borderColor() -> Binder<UIColor?> {
        Binder(self.base) { view, color in
            if let co = color {
                view.layer.borderColor = co.cgColor
                view.layer.borderWidth = 1
            }
        }
    }
    
    public func backgroundColor() -> Binder<UIColor?> {
        Binder(self.base) { view, color in
            view.backgroundColor = color
        }
    }
    
    public func cornerRadius() -> Binder<CGFloat> {
        Binder(self.base) { view, radius in
            view.layer.cornerRadius = radius
        }
    }
}

extension Reactive where Base: UIView {
    
    public func addTap() -> ControlEvent<()> {
        let source: Observable<Void> = Observable.create { [weak control = self.base] observer in
                MainScheduler.ensureRunningOnMainThread()

                guard let control = control else {
                    observer.on(.completed)
                    return Disposables.create()
                }

                let tap = UITapGestureRecognizer.init()
                control.addGestureRecognizer(tap)
                _ = tap.rx.event.subscribe { tap in
                    
                    observer.on(.next(()))
                    observer.onCompleted()
                }

                
                
                return Disposables.create()
            }
            .take(until: deallocated)

        return ControlEvent(events: source)
    }
}
